<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="700px"
      :before-close="cancel"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-scrollbar style="height: 600px">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          size="small"
          label-width="150px"
        >
          <el-form-item label="软件名称" prop="softwareName">
            <el-input
              v-model="form.softwareName"
              :disabled="historyDisabled"
              style="width: 80%"
              maxlength="100"
              show-word-limit
              placeholder="请输入软件名称"
            />
          </el-form-item>
          <el-form-item label="软件制作时间" prop="softwareCreateTime">
            <div class="el-datetime-width">
              <el-date-picker
                v-model="form.softwareCreateTime"
                :disabled="historyDisabled"
                style="width: 80%"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择软件制作时间"
              />
            </div>
          </el-form-item>
          <el-form-item label="软件制作人" prop="softwareCreater">
            <el-input
              v-model="form.softwareCreater"
              :disabled="historyDisabled"
              style="width: 80%"
              placeholder="请输入软件制作人"
            />
          </el-form-item>
          <el-form-item label="软件版本" prop="softwareVersion">
            <el-input
              v-model="form.softwareVersion"
              :disabled="historyDisabled"
              style="width: 80%"
              placeholder="请输入软件版本"
            />
          </el-form-item>
          <el-form-item label="软件描述" prop="softwareDesc">
            <el-input
              v-model="form.softwareDesc"
              :disabled="historyDisabled"
              style="width: 80%"
              type="textarea"
              maxlength="500"
              show-word-limit
              placeholder="请输入软件描述"
            />
          </el-form-item>
          <el-form-item label="系统类型" prop="typeArr">
            <el-select
              v-model="form.typeArr"
              :disabled="historyDisabled"
              style="width: 80%"
              clearable
              placeholder="请选择系统类型"
              :multiple="true"
            >
              <el-option
                v-for="item in systemTypeList"
                :key="item.value"
                :label="item.value"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="软件类型" prop="softwareType">
            <el-select
              v-model="form.softwareType"
              :disabled="historyDisabled"
              style="width: 80%"
              clearable
              placeholder="请选择软件类型"
            >
              <el-option
                v-for="item in softwareTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="位数" prop="ws">
            <el-select
              v-model="form.ws"
              :disabled="historyDisabled"
              style="width: 80%"
              clearable
              placeholder="请选择位数"
            >
              <el-option
                v-for="item in wsList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="是否自动化部署" prop="auto">
            <el-radio v-model="form.auto" :disabled="historyDisabled" label="1"
              >是</el-radio
            >
            <el-radio v-model="form.auto" :disabled="historyDisabled" label="0"
              >否</el-radio
            >
          </el-form-item>
          <el-form-item label="资源检查规则">
            <div v-for="(domain, index) in form.rules" :key="domain.key">
              <!-- 除path外变量 -->
              <div :style="{ marginTop: index !== 0 ? '5px' : '0px' }">
                <el-input
                  v-model="domain.minvalue"
                  oninput="value=value.replace(/[^0-9]/g,'')"
                  placeholder="请填写所需资源最小值"
                  class="domain-input-wrapper"
                  :disabled="historyView"
                >
                  <template slot="prepend">
                    <el-select
                      v-model="domain.item"
                      placeholder="类型"
                      style="width: 110px"
                      :disabled="historyView"
                    >
                      <el-option
                        label="磁盘"
                        value="磁盘"
                        :disabled="domainIitemDisable('磁盘')"
                      ></el-option>
                      <el-option
                        label="内存"
                        value="内存"
                        :disabled="domainIitemDisable('内存')"
                      ></el-option>
                      <!-- <el-option label="网络" value="网络"></el-option>
                      <el-option label="CPU" value="CPU"></el-option>-->
                    </el-select>
                  </template>

                  <template slot="append">
                    <el-select
                      v-model="domain.unit"
                      style="width: 110px"
                      placeholder="单位"
                      :disabled="historyView"
                    >
                      <!-- <el-option label="KB" value="KB"></el-option> -->
                      <el-option label="MB" value="MB"></el-option>
                      <el-option label="GB" value="GB"></el-option>
                    </el-select>
                  </template>
                </el-input>
                <el-button
                  style="margin-left: 5px"
                  size="mini"
                  @click.prevent="addDomain(domain)"
                  icon="el-icon-plus"
                  circle
                  :disabled="historyView"
                ></el-button>
                <el-button
                  style="margin-left: 5px"
                  size="mini"
                  @click.prevent="removeDomain(domain)"
                  icon="el-icon-minus"
                  circle
                  :disabled="historyView"
                ></el-button>

                <!-- <el-select
                  v-model="domain.item"
                  style="width: 20%"
                  placeholder="类型"
                  :disabled="historyDisabled"
                >
                  <el-option label="磁盘" value="磁盘"></el-option>
                  <el-option label="内存" value="内存"></el-option>
                  <el-option label="网络" value="网络"></el-option>
                  <el-option label="CPU" value="CPU"></el-option>
                </el-select>
                <el-input
                  style="width: 40%"
                  v-model="domain.minvalue"
                  oninput="value=value.replace(/[^0-9]/g,'')"
                  placeholder="请填写所需资源最小值"
                  :disabled="historyDisabled"
                ></el-input>

                <el-select
                  v-model="domain.unit"
                  style="width: 20%"
                  placeholder="单位"
                  :disabled="historyDisabled"
                >
                  <el-option label="KB" value="KB"></el-option>
                  <el-option label="MB" value="MB"></el-option>
                  <el-option label="GB" value="GB"></el-option>
                </el-select>
                <el-button
                  style="margin-left: 5px"
                  size="mini"
                  @click.prevent="addDomain(domain)"
                  icon="el-icon-plus"
                  :disabled="historyDisabled"
                  circle
                ></el-button>
                <el-button
                  style="margin-left: 5px"
                  size="mini"
                  @click.prevent="removeDomain(domain)"
                  icon="el-icon-minus"
                  :disabled="historyDisabled"
                  circle
                ></el-button>-->
              </div>
            </div>
          </el-form-item>
          <el-form-item
            v-if="form.auto == '1' || form.auto == '0'"
            label="软件上传"
            prop="softwareUpload"
          >
            <fileUpload
              ref="upload"
              :flag="fileUploadFlag"
              :limit="1"
              :fileSize="1024 * 4"
              :file-type="['rar', 'zip', '7z']"
              :value="form.softwareFile"
              @input="getSoftwareFile"
              @fileChange="changeSoftwareFile"
            />
          </el-form-item>
          <el-divider v-if="form.auto == '1'" class="pathDivider"></el-divider>
          <el-form-item
            v-if="form.auto == '1'"
            label="环境变量录入方式"
            prop="varIntroductionWay"
          >
            <el-radio
              @input="wayChange"
              :disabled="fileUploadFlag"
              v-model="form.varIntroductionWay"
              label="上传"
              >上传</el-radio
            >
            <el-radio
              @input="wayChange"
              :disabled="fileUploadFlag"
              v-model="form.varIntroductionWay"
              label="手动填写"
              >手动填写</el-radio
            >
          </el-form-item>
          <el-form-item
            v-if="form.auto == '1' && form.varIntroductionWay === '上传'"
            label="环境变量脚本上传"
            prop="varScriptUpload"
          >
            <fileUpload
              :limit="1"
              :flag="fileUploadFlag"
              ref="varScriptUpload"
              :file-type="['bat', 'sh']"
              :value="form.varScriptFile"
              @input="getVarScriptFile"
              @fileChange="changeVarScriptFile"
            />
          </el-form-item>
          <el-form-item
            v-if="form.auto == '1' && form.varIntroductionWay === '手动填写'"
            label="环境变量"
            prop="varScriptUpload"
          >
            <el-button type="primary" size="mini" @click="openEnvVarForm"
              >填写环境变量</el-button
            >
          </el-form-item>
          <el-divider v-if="form.auto == '1'" class="pathDivider"></el-divider>
          <el-form-item
            v-if="form.auto == '1'"
            label="软件安装脚本上传"
            prop="insScriptUpload"
          >
            <el-button
              @click="handleInstall"
              size="mini"
              type="primary"
              :disabled="historyView"
              >选取文件</el-button
            >
            <span style="margin-left: 12px; color: #f56c6c"
              >此处应上传软件安装脚本，请仔细确认</span
            >
            <fileUpload
              :limit="1"
              :flag="fileUploadFlag"
              ref="insScriptUpload"
              :file-type="['bat', 'sh']"
              :value="form.softwareInsFile"
              @input="getSoftwareInsFile"
              @fileChange="changeSoftwareInsFile"
              :showBtn="false"
              class="install-upload"
            >
            </fileUpload>
          </el-form-item>
          <el-divider v-if="form.auto == '1'" class="pathDivider"></el-divider>
          <el-form-item
            v-if="form.auto == '1'"
            label="软件启动录入方式"
            prop="softwareStartupWay"
          >
            <el-radio
              @input="startupWayChange"
              :disabled="fileUploadFlag"
              v-model="form.softwareStartupWay"
              label="上传"
              >上传</el-radio
            >
            <el-radio
              @input="startupWayChange"
              :disabled="fileUploadFlag"
              v-model="form.softwareStartupWay"
              label="手动填写"
              >手动填写</el-radio
            >
          </el-form-item>
          <el-form-item
            v-if="form.auto == '1' && form.softwareStartupWay === '上传'"
            label="软件启动脚本上传"
            prop="runScriptUpload"
          >
            <fileUpload
              :limit="1"
              :flag="fileUploadFlag"
              ref="runScriptUpload"
              :file-type="['bat', 'sh']"
              :value="form.runScriptFile"
              @input="getRunScriptFile"
              @fileChange="changeRunScriptFile"
            >
              <span slot="customText" style="margin-left: 12px; color: #f56c6c"
                >此处应上传软件启动脚本，请仔细确认</span
              >
            </fileUpload>
          </el-form-item>
          <el-form-item
            v-if="form.auto == '1' && form.softwareStartupWay === '手动填写'"
            label="软件启动"
            prop="runScriptUpload"
          >
            <el-button type="primary" size="mini" @click="openStartSoftwareForm"
              >填写启动路径</el-button
            >
          </el-form-item>
          <el-divider v-if="form.auto == '1'" class="pathDivider"></el-divider>
          <el-form-item
            v-if="form.auto == '1'"
            label="软件停止录入方式"
            prop="softwareStopWay"
          >
            <el-radio
              @input="stopWayChange"
              :disabled="fileUploadFlag"
              v-model="form.softwareStopWay"
              label="上传"
              >上传</el-radio
            >
            <el-radio
              @input="stopWayChange"
              :disabled="fileUploadFlag"
              v-model="form.softwareStopWay"
              label="手动填写"
              >手动填写</el-radio
            >
            <el-radio
              @input="stopWayChange"
              :disabled="fileUploadFlag"
              v-model="form.softwareStopWay"
              :label="stopWayThirdText"
              >{{ stopWayThirdText }}</el-radio
            >
          </el-form-item>
          <el-form-item
            v-if="form.auto == '1' && form.softwareStopWay === '上传'"
            label="软件停止脚本上传"
            prop="stopScriptUpload"
          >
            <fileUpload
              :limit="1"
              :flag="fileUploadFlag"
              ref="stopScriptUpload"
              :file-type="['bat', 'sh']"
              :value="form.stopScriptFile"
              @input="getStopScriptFile"
              @fileChange="changeStopScriptFile"
            />
          </el-form-item>
          <el-form-item
            v-if="form.auto == '1' && form.softwareStopWay === '手动填写'"
            label="软件停止"
            prop="stopScriptUpload"
          >
            <el-button type="primary" size="mini" @click="openStopSoftwareForm"
              >填写停止路径</el-button
            >
          </el-form-item>
          <el-divider v-if="form.auto == '1'" class="pathDivider"></el-divider>
          <el-form-item
            v-if="form.auto == '1'"
            label="软件卸载脚本上传"
            prop="uninsScriptUpload"
          >
            <fileUpload
              :limit="1"
              :flag="fileUploadFlag"
              ref="uninsScriptUpload"
              :file-type="['bat', 'sh']"
              :value="form.softwareUninsFile"
              @input="getSoftwareUninsFile"
              @fileChange="changeSoftwareUninsFile"
            />
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="addFlag" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="软件详情"
      :visible.sync="changeDetailVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-descriptions
        class="margin-top"
        title=""
        :column="2"
        :size="size"
        border
        :labelStyle="{ width: '130px' }"
      >
        <el-descriptions-item span="2">
          <template slot="label"> 软件名称： </template>
          {{ form.softwareName }}
        </el-descriptions-item>
        <el-descriptions-item span="2">
          <template slot="label"> 软件类型 </template>
          {{ form.softwareType == "0" ? "专用软件" : "基础软件" }}
        </el-descriptions-item>
        <el-descriptions-item span="2">
          <template slot="label"> 是否自动化部署 </template>
          {{ form.auto == "1" ? "是" : "否" }}
        </el-descriptions-item>
      </el-descriptions>

      <template v-if="form.auto == '1'">
        <div style="font-size: 14px; margin: 12px 0">
          软件自动化部署设置情况
        </div>
        <el-descriptions
          class="margin-top"
          title=""
          :column="2"
          :size="size"
          border
        >
          <el-descriptions-item>
            <template slot="label"> 环境变量 </template>
            {{ varFlag ? "有" : "无" }}
            <template v-if="varFlag">
              <span style="margin-left: 16px">{{
                form.varIntroductionWay == "上传"
                  ? "脚本上传"
                  : form.varIntroductionWay
              }}</span>
            </template>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 软件安装脚本 </template>
            {{ installFlag ? "有" : "无" }}
            <template v-if="installFlag">
              <span style="margin-left: 16px">脚本上传</span>
            </template>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 软件启动设置 </template>
            {{ startFlag ? "有" : "无" }}
            <template v-if="startFlag">
              <span style="margin-left: 16px">{{
                form.softwareStartupWay == "上传"
                  ? "脚本上传"
                  : form.softwareStartupWay
              }}</span>
            </template>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 软件停止设置 </template>
            {{ stopFlag ? "有" : "无" }}
            <template v-if="stopFlag">
              <span style="margin-left: 16px">{{
                form.softwareStopWay == "上传"
                  ? "脚本上传"
                  : form.softwareStopWay
              }}</span>
            </template>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 软件卸载设置 </template>
            {{ unstallFlag ? "有" : "无" }}
            <template v-if="unstallFlag">
              <span style="margin-left: 16px">脚本上传</span>
            </template>
          </el-descriptions-item>
        </el-descriptions>
      </template>

      <span slot="footer" class="dialog-footer">
        <el-button @click="changeDetailVisible = false">取消</el-button>
        <el-button type="primary" @click="changeDetailConfirm">确定</el-button>
      </span>
    </el-dialog>
    <!-- 修改二次确认弹窗，是否生成新版本历史 -->
    <el-dialog
      title="提示"
      :visible.sync="editConfirmVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-alert
        title="是否添加为新版本？"
        type="warning"
        show-icon
        :closable="false"
      ></el-alert>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setCancle">否</el-button>
        <el-button type="primary" @click="setConfirm">是</el-button>
      </span>
    </el-dialog>
    <!-- 确定新版本填写版本号弹窗 -->
    <el-dialog
      title="确认版本号"
      :visible.sync="setVisionVisible"
      :close-on-click-modal="false"
      width="30%"
    >
      <span>版本号：</span>
      <el-input
        v-model="newVision"
        style="width: 70%"
        placeholder="请填写版本号"
      ></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancleNewVision">取 消</el-button>
        <el-button type="primary" @click="confirmNewVision">确 定</el-button>
      </span>
    </el-dialog>
    <env-var-form
      ref="envVarFormRef"
      @saveEnvVarForm="saveEnvVarForm"
      :flag="fileUploadFlag"
    ></env-var-form>
    <start-software
      ref="startSoftwareRef"
      @saveStartSoftwareForm="saveStartSoftwareForm"
      :flag="fileUploadFlag"
    ></start-software>
    <stop-software
      ref="stopSoftwareRef"
      @saveStopSoftwareForm="saveStopSoftwareForm"
      :flag="fileUploadFlag"
    ></stop-software>
  </div>
</template>

<script>
import {
  getSoftware,
  addSoftware,
  updateSoftwareForNew,
  updateSoftwareNotForNew,
  getOsList,
} from "@/api/resource/modelSoftware.js";
import { getHistoryById } from "@/api/resource/software-history.js";
import envVarForm from "@/views/resource/modelSoftware/components/envVarForm";
import startSoftware from "@/views/resource/modelSoftware/components/startSoftware";
import stopSoftware from "@/views/resource/modelSoftware/components/stopSoftware";
export default {
  components: { envVarForm, startSoftware, stopSoftware },
  data() {
    return {
      // 修改二次确认弹窗
      editConfirmVisible: false,
      //软件类型
      softwareTypeList: [
        { value: "0", label: "专用软件" },
        { value: "1", label: "基础软件" },
      ],
      //位数
      wsList: [
        { value: "全部", label: "全部" },
        { value: "64", label: "64" },
        { value: "32", label: "32" },
      ],
      //系统类型
      //systemTypeList: [{ value: 'linux' }, { value: 'windows' }],
      systemTypeList: [],
      // 添加标识
      addFlag: true,
      // 表单项是否可编辑
      historyDisabled: false,
      historyView: false,
      form: {
        softwareName: void 0,
        softwareDesc: void 0,
        softwareCreateTime: void 0,
        softwareCreater: void 0,
        type: void 0,
        typeArr: [],
        ws: void 0,
        softwareFile: "",
        varScriptFile: "",
        softwareInsFile: "",
        runScriptFile: "",
        stopScriptFile: "",
        softwareUninsFile: "",
        changeSoftwareFile: "",
        changeVarScriptFile: "",
        changeRunScriptFile: "",
        changeSoftwareUninsFile: "",
        changeSoftwareInsFile: "",
        changeStopScriptFile: "",
        softwareType: void 0,
        rule: void 0,
        auto: "1",
        softwareVersion: void 0,
        varIntroductionWay: "上传",
        envVarFormData: {},
        softwareEnv: [],
        softwareStartupWay: "上传",
        startSoftwareFormData: {},
        softwareStopWay: "上传",
        stopSoftwareFormData: {},
        rules: [{ item: "", minvalue: "", unit: "" }],
      },
      // 表单校验
      rules: {
        softwareName: [
          { required: true, message: "软件名称不能为空", trigger: "blur" },
        ],
        softwareDesc: [
          { required: true, message: "软件描述不能为空", trigger: "blur" },
        ],
        typeArr: [
          { required: true, message: "系统类型不能为空", trigger: "change" },
        ],
        ws: [{ required: true, message: "位数不能为空", trigger: "change" }],
        softwareCreateTime: [
          { required: true, message: "软件制作时间不能为空", trigger: "blur" },
        ],
        softwareCreater: [
          { required: true, message: "软件制作人不能为空", trigger: "blur" },
        ],
        softwareVersion: [
          { required: true, message: "软件版本不能为空", trigger: "blur" },
        ],
        softwareUpload: [
          { required: true, trigger: "blur", validator: this.validateFiles },
        ],
        softwareType: [
          { required: true, trigger: "change", message: "软件类型不能为空" },
        ],
        // rule: [
        //   { required: true, trigger: 'blur', message: '资源检查规则' }
        // ],
        auto: [
          {
            required: true,
            trigger: "change",
            message: "是否自动化部署不能为空",
          },
        ],
      },
      // 弹窗控制
      open: false,
      // 弹窗标题
      title: "",
      // 新版本号弹窗控制
      setVisionVisible: false,
      // 修改确定新版本版本号
      newVision: void 0,
      // 环境变量脚本列表
      varScriptFileList: [],
      // 软件启动脚本列表
      runScriptFileList: [],
      // 软件停止脚本列表
      stopScriptFileList: [],
      // 通过程序停止的选项名称
      stopWayThirdText: "通过程序名称结束",
      changeDetailVisible: false,
    };
  },
  computed: {
    // 计算属性的 getter
    domainIitemDisable() {
      return function (val) {
        if (this.form.rules.length > 1) {
          return this.form.rules.some((it) => it.item == val);
        } else {
          return false;
        }
      };
    },
    // 环境变量有无
    varFlag() {
      // 根据两种方式判断 上传文件的和手动填写
      let flag = false;
      if (this.form.varIntroductionWay == "上传") {
        flag = Boolean(this.form.varScriptFile);
      } else {
        // 选择手动填写，需要判断，是否添加了系统变量和用户变量
        flag =
          this.form.envVarFormData.systemForm.domains.some(
            (item) => item.varValue !== ""
          ) ||
          this.form.envVarFormData.userForm.domains.some(
            (item) => item.varValue !== ""
          );
      }
      return flag;
    },
    installFlag() {
      return Boolean(this.form.softwareInsFile);
    },
    startFlag() {
      // 根据两种方式判断 上传文件的和手动填写
      let flag = false;
      if (this.form.softwareStartupWay == "上传") {
        flag = Boolean(this.form.runScriptFile);
      } else {
        // 选择手动填写，启动路径是否填写
        flag = Boolean(this.form.startSoftwareFormData.startPath);
      }
      return flag;
    },
    stopFlag() {
      let flag = false;
      if (this.form.softwareStopWay == "上传") {
        flag = Boolean(this.form.stopScriptFile);
      } else if (this.form.softwareStopWay == "手动填写") {
        // 选择手动填写，启动路径是否填写
        flag = Boolean(this.form.stopSoftwareFormData.stopPath);
      } else {
        // 程序名称
        flag = true;
      }
      return flag;
    },
    unstallFlag() {
      return Boolean(this.form.softwareUninsFile);
    },
  },
  created() {
    getOsList().then((res) => {
      res.data.forEach((e) => {
        this.systemTypeList.push({ value: e.name });
      });
    });
  },
  methods: {
    handleInstall() {
      console.log(
        "insScriptUpload",
        this.$refs.insScriptUpload.$refs.uploadBtn
      );

      this.$confirm("请确认上传脚本为软件安装脚本", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$refs.insScriptUpload.$refs.uploadBtn.$vnode.elm.click();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消上传安装脚本",
          });
        });
    },
    confirmNewVision() {
      this.form.softwareVersion = this.newVision;
      this.$modal.loading("正在保存，请稍候...");
      updateSoftwareForNew(this.form).then((res) => {
        if (res.code == 200) {
          this.setVisionVisible = false;
          this.cancel();
          this.editConfirmVisible = false;
          this.$modal.msgSuccess("添加成功");
          this.$emit("ok");
        } else {
          this.$modal.msgError(res.msg);
        }
        this.$modal.closeLoading();
      });
    },
    cancleNewVision() {
      this.setVisionVisible = false;
    },
    addOpen() {
      this.resetSoftware();
      this.historyDisabled = false;
      this.addFlag = true;
      this.open = true;
      this.title = "新增模型";
    },
    // 点击修改弹框
    editOpen(row) {
      this.resetSoftware();
      this.addFlag = true;
      this.delText = "";
      const softwareId = row.softwareId;
      this.historyDisabled = true;
      getSoftware(softwareId).then((response) => {
        console.log("打印 修改response", response);
        this.form = response.data;
        this.form.typeArr = response.data.type.split(",");
        this.form.changeSoftwareFile = false;
        this.form.changeVarScriptFile = false;
        this.form.changeRunScriptFile = false;
        this.form.changeSoftwareUninsFile = false;
        this.form.changeSoftwareInsFile = false;
        this.form.changeStopScriptFile = false;
        // 判断资源检查规则
        if (response.data.rules.length > 0) {
          this.form.rules = response.data.rules;
        } else {
          this.form.rules = [{ item: "", minvalue: "", unit: "" }];
        }
        if (this.form.varIntroductionWay === "手动填写") {
          this.form.softwareEnv =
            this.form.envVarFormData.userForm.domains.concat(
              this.form.envVarFormData.systemForm.domains
            );
        }
        this.open = true;
        this.title = "修改模型";
        // 文件回显
        this.$nextTick(() => {
          if (response.data.historySoftwareFileList) {
            let arr1 = [];
            arr1.push(response.data.historySoftwareFileList);
            this.$refs.upload.fileList = arr1;
            this.form.softwareFile = arr1[0].fileId;
          }
          if (response.data.historyVarScriptFileList) {
            let arr2 = [];
            arr2.push(response.data.historyVarScriptFileList);
            if (this.$refs.varScriptUpload) {
              this.$refs.varScriptUpload.fileList = arr2;
            }
            this.form.varScriptFile = arr2[0].fileId;
            this.varScriptFileList = JSON.parse(JSON.stringify(arr2));
          }
          if (response.data.historyRunScriptFileList) {
            let arr3 = [];
            arr3.push(response.data.historyRunScriptFileList);
            if (this.$refs.runScriptUpload) {
              this.$refs.runScriptUpload.fileList = arr3;
            }
            this.form.runScriptFile = arr3[0].fileId;
            this.runScriptFileList = JSON.parse(JSON.stringify(arr3));
          }
          if (response.data.historySoftwareUninsFileList) {
            let arr4 = [];
            arr4.push(response.data.historySoftwareUninsFileList);
            this.$refs.uninsScriptUpload.fileList = arr4;
            this.form.softwareUninsFile = arr4[0].fileId;
          }
          if (response.data.historySoftwareInsFileList) {
            let arr5 = [];
            arr5.push(response.data.historySoftwareInsFileList);
            this.$refs.insScriptUpload.fileList = arr5;
            this.form.softwareInsFile = arr5[0].fileId;
          }
          if (response.data.historyStopScriptFileList) {
            let arr6 = [];
            arr6.push(response.data.historyStopScriptFileList);
            if (this.$refs.stopScriptUpload) {
              this.$refs.stopScriptUpload.fileList = arr6;
            }
            this.form.stopScriptFile = arr6[0].fileId;
            this.stopScriptFileList = JSON.parse(JSON.stringify(arr6));
          }
        });
      });
    },
    async historyOpen(row) {
      // 表单不可修改
      this.historyDisabled = true;
      this.historyView = true;
      // 重置表单
      this.resetSoftware();
      // 是否新增标识
      this.addFlag = false;
      // 弹窗显影标识
      this.open = true;
      // 文件上传组件按钮不可点击标识
      this.fileUploadFlag = true;
      this.title = "历史版本查看";
      const { data } = await getHistoryById(row.id);
      this.form.softwareId = data.softwareId;
      this.form.softwareName = data.historyName;
      this.form.softwareVersion = data.historyVersion;
      this.form.type = data.type;
      this.form.typeArr = data.type.split(",");
      this.form.softwareCreateTime = data.historyCreateTime;
      this.form.softwareCreater = data.historyCreater;
      this.form.softwareDesc = data.historySoftwareDesc;
      this.form.softwareType = data.softwareType;
      this.form.rule = data.rule;
      this.form.auto = data.auto;
      this.form.ws = data.ws;
      this.form.varIntroductionWay = data.historyVarIntroductionWay;
      if (this.form.varIntroductionWay === "手动填写") {
        this.form.envVarFormData = data.envVarFormData;
        this.form.softwareEnv =
          this.form.envVarFormData.userForm.domains.concat(
            this.form.envVarFormData.systemForm.domains
          );
      }
      if (this.form.softwareStartupWay === "手动填写") {
        this.form.startSoftwareFormData = data.startSoftwareFormData;
      }
      if (this.form.softwareStopWay === "手动填写") {
        this.form.stopSoftwareFormData = data.stopSoftwareFormData;
      }

      this.form.changeSoftwareFile = false;
      this.form.changeVarScriptFile = false;
      this.form.changeRunScriptFile = false;
      this.form.changeSoftwareUninsFile = false;
      this.form.changeSoftwareInsFile = false;
      this.form.changeStopScriptFile = false;
      if (data.historySoftwareFileList) {
        let arr1 = [];
        arr1.push(data.historySoftwareFileList);
        this.$refs.upload.fileList = arr1;
        this.form.softwareFile = arr1[0].fileId;
      }
      if (data.historyVarScriptFileList) {
        let arr2 = [];
        arr2.push(data.historyVarScriptFileList);
        this.$refs.varScriptUpload.fileList = arr2;
        this.form.varScriptFile = arr2[0].fileId;
      }
      if (data.historyRunScriptFileList) {
        let arr3 = [];
        arr3.push(data.historyRunScriptFileList);
        this.$refs.runScriptUpload.fileList = arr3;
        this.form.runScriptFile = arr3[0].fileId;
      }
      if (data.historySoftwareUninsFileList) {
        let arr4 = [];
        arr4.push(data.historySoftwareUninsFileList);
        this.$refs.uninsScriptUpload.fileList = arr4;
        this.form.softwareUninsFile = arr4[0].fileId;
      }
      if (data.historySoftwareInsFileList) {
        let arr5 = [];
        arr5.push(data.historySoftwareInsFileList);
        this.$refs.insScriptUpload.fileList = arr5;
        this.form.softwareInsFile = arr5[0].fileId;
      }
      if (data.historyStopScriptFileList) {
        let arr6 = [];
        arr6.push(data.historyStopScriptFileList);
        this.$refs.stopScriptUpload.fileList = arr6;
        this.form.stopScriptFile = arr6[0].fileId;
      }
      // 判断资源检查规则
      if (data.rules.length > 0) {
        this.form.rules = data.rules;
      } else {
        this.form.rules = [{ item: "", minvalue: "", unit: "" }];
      }
    },
    setConfirm() {
      this.newVision = "";
      this.setVisionVisible = true;
      // this.$modal.loading('正在保存，请稍候...')
      // updateSoftwareForNew(this.form).then(res => {
      //   if (res.code == 200) {
      //     this.cancel()
      //     this.$modal.closeLoading()
      //     this.editConfirmVisible = false
      //     this.$modal.msgSuccess('添加成功')
      //     this.$emit('ok')
      //   }
      // })
    },
    setCancle() {
      this.$modal.loading("正在保存，请稍候...");
      updateSoftwareNotForNew(this.form).then((res) => {
        if (res.code == 200) {
          this.cancel();
          this.$modal.closeLoading();
          this.editConfirmVisible = false;
          this.$modal.msgSuccess("更新成功");
          this.$emit("ok");
        } else {
          this.$modal.msgError(res.msg);
        }
        this.$modal.closeLoading();
      });
    },
    /** 提交按钮 */
    submitForm() {
      // 校验资源检查规则
      // if (!this.validFormRules()) {
      //   return;
      // }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.softwareStopWay === this.stopWayThirdText) {
            if (this.form.softwareStartupWay === "上传") {
              this.$modal.msgError(
                "停止方式选择" +
                  this.stopWayThirdText +
                  ",启动录入方式需要手动上传"
              );
              return;
            }
            if (
              this.validatenull(this.form.startSoftwareFormData) ||
              this.validatenull(this.form.startSoftwareFormData.startPath)
            ) {
              this.$modal.msgError("启动录入方式不能为空");
              return;
            }
          }
          // 弹出概览
          this.changeDetailVisible = true;
        }
      });
    },
    // 表单取消按钮
    cancel() {
      this.open = false;
      this.resetSoftware();
      this.clearFileList();
      this.$emit("ok");
    },
    // 软件详情详情改变事件
    changeDetailConfirm() {
      this.changeDetailVisible = false;
      // 开始走 新增和修改的逻辑
      this.form.type = this.form.typeArr.join(",");
      if (this.form.softwareId !== undefined && this.form.softwareId !== null) {
        this.editConfirmVisible = true;
      } else {
        addSoftware(this.form).then((response) => {
          if (response.code == 200) {
            this.$modal.msgSuccess("新增成功");
            this.resetForm("form");
            this.open = false;
            this.clearFileList();
            this.$emit("ok");
          } else {
            this.$modal.msgError(response.msg);
          }
        });
      }
    },
    // 表单重置
    resetSoftware() {
      this.form = {
        softwareName: "",
        softwareDesc: "",
        softwareCreateTime: "",
        softwareCreater: "",
        type: "",
        typeArr: [],
        softwareFile: "",
        varScriptFile: "",
        softwareInsFile: "",
        runScriptFile: "",
        stopScriptFile: "",
        softwareUninsFile: "",
        changeSoftwareFile: false,
        changeVarScriptFile: false,
        changeRunScriptFile: false,
        changeSoftwareUninsFile: false,
        changeSoftwareInsFile: false,
        changeStopScriptFile: false,
        softwareType: "",
        ws: "",
        rule: void 0,
        auto: "1",
        softwareVersion: void 0,
        varIntroductionWay: "上传",
        envVarFormData: {},
        softwareEnv: [],
        softwareStartupWay: "上传",
        startSoftwareFormData: {},
        softwareStopWay: "上传",
        stopSoftwareFormData: {},
        rules: [{ item: "", minvalue: "", unit: "" }],
      };
      this.resetForm("form");
      this.varScriptFileList = [];
      this.runScriptFileList = [];
      this.stopScriptFileList = [];
    },
    clearFileList() {
      if (this.$refs.upload) {
        this.$refs.upload.fileList = [];
      }
      if (this.$refs.varScriptUpload) {
        this.$refs.varScriptUpload.fileList = [];
      }
      if (this.$refs.runScriptUpload) {
        this.$refs.runScriptUpload.fileList = [];
      }
      if (this.$refs.uninsScriptUpload) {
        this.$refs.uninsScriptUpload.fileList = [];
      }
      if (this.$refs.insScriptUpload) {
        this.$refs.insScriptUpload.fileList = [];
      }
      if (this.$refs.stopScriptUpload) {
        this.$refs.stopScriptUpload.fileList = [];
      }
    },
    // 校验文件
    validateFiles(rule, value, callback) {
      let files = this.$refs.upload.fileList;
      if (files.length === 0) {
        callback(new Error("文件不能为空"));
      }
      callback();
    },
    resetFormRule(formPropFeild) {
      this.$refs.form.clearValidate([formPropFeild]);
    },
    // 获取软件文件
    getSoftwareFile(fileList) {
      if (fileList.length > 0) {
        this.form.softwareFile = fileList[0].fileId;
        this.resetFormRule("softwareUpload");
      } else {
        this.form.softwareFile = null;
      }
    },
    // 软件文件是否改变标识
    changeSoftwareFile(bool) {
      this.form.changeSoftwareFile = bool;
    },
    // 获取环境变量脚本文件
    getVarScriptFile(fileList) {
      if (fileList.length > 0) {
        this.form.varScriptFile = fileList[0].fileId;
        this.varScriptFileList = JSON.parse(JSON.stringify(fileList));
        this.resetFormRule("varScriptUpload");
      } else {
        this.form.varScriptFile = null;
        this.varScriptFileList = [];
      }
    },
    // 环境变量是否改变标识
    changeVarScriptFile(bool) {
      this.form.changeVarScriptFile = bool;
    },
    // 安装脚本文件
    getSoftwareInsFile(fileList) {
      if (fileList.length > 0) {
        this.form.softwareInsFile = fileList[0].fileId;
        this.resetFormRule("insScriptUpload");
      } else {
        this.form.softwareInsFile = null;
      }
    },
    // 安装脚本是否改变标识
    changeSoftwareInsFile(bool) {
      this.form.changeSoftwareInsFile = bool;
    },
    // 获取软件启动脚本
    getRunScriptFile(fileList) {
      if (fileList.length > 0) {
        this.form.runScriptFile = fileList[0].fileId;
        this.resetFormRule("runScriptUpload");
      } else {
        this.form.runScriptFile = null;
      }
    },
    // 启动脚本是否改变标识
    changeRunScriptFile(bool) {
      this.form.changeRunScriptFile = bool;
    },
    getStopScriptFile(fileList) {
      if (fileList.length > 0) {
        this.form.stopScriptFile = fileList[0].fileId;
        this.resetFormRule("stopScriptUpload");
      } else {
        this.form.stopScriptFile = null;
      }
    },
    changeStopScriptFile(bool) {
      this.form.changeStopScriptFile = bool;
    },
    getSoftwareUninsFile(fileList) {
      if (fileList.length > 0) {
        this.form.softwareUninsFile = fileList[0].fileId;
        this.resetFormRule("uninsScriptUpload");
      } else {
        this.form.softwareUninsFile = null;
      }
    },
    changeSoftwareUninsFile(bool) {
      this.form.changeSoftwareUninsFile = bool;
    },
    // 打开环境变量表单
    openEnvVarForm() {
      this.$refs.envVarFormRef.openDialog(
        JSON.parse(JSON.stringify(this.form.envVarFormData))
      );
    },
    // 保存环境变量表单数据
    saveEnvVarForm(data) {
      this.form.envVarFormData = data;
      this.form.softwareEnv = data.userForm.domains.concat(
        data.systemForm.domains
      );
    },
    // 监听环境变量录入方式修改
    wayChange(val) {
      if (val === "上传") {
        // this.form.envVarFormData = {}
        // this.form.softwareEnv = []
        if (!this.validatenull(this.varScriptFileList)) {
          this.$nextTick(() => {
            this.$refs.varScriptUpload.fileList = JSON.parse(
              JSON.stringify(this.varScriptFileList)
            );
          });
        } else {
          this.$nextTick(() => {
            this.$refs.varScriptUpload.fileList = [];
          });
        }
      } else {
        if (this.validatenull(this.form.envVarFormData)) {
          const data = {
            userForm: {
              domains: [
                {
                  varName: "path",
                  varValue: "",
                  varWay: "追加",
                  dataType: "user",
                },
              ],
            },
            systemForm: {
              domains: [
                {
                  varName: "path",
                  varValue: "",
                  varWay: "追加",
                  dataType: "system",
                },
              ],
            },
          };
          this.form.envVarFormData = data;
          this.form.softwareEnv = data.userForm.domains.concat(
            data.systemForm.domains
          );
        }
      }
    },
    // 监听软件启动脚本录入方式修改
    startupWayChange(val) {
      if (val === "上传") {
        console.log("1111111", this.runScriptFileList);
        // this.form.startSoftwareFormData = {}
        if (!this.validatenull(this.runScriptFileList)) {
          this.$nextTick(() => {
            console.log("点击软件启动上传");
            this.$refs.runScriptUpload.fileList = JSON.parse(
              JSON.stringify(this.runScriptFileList)
            );
          });
        } else {
          this.$nextTick(() => {
            this.$refs.runScriptUpload.fileList = [];
          });
        }
      } else {
        if (this.validatenull(this.form.startSoftwareFormData)) {
          const data = {
            isDepPath: "绝对路径",
            startPath: "",
            exeName: "",
          };
          this.form.startSoftwareFormData = data;
        }
      }
    },
    // 保存软件启动表单数据
    saveStartSoftwareForm(data) {
      this.form.startSoftwareFormData = data;
    },
    // 打开启动脚本表单
    openStartSoftwareForm() {
      this.$refs.startSoftwareRef.openDialog(
        JSON.parse(JSON.stringify(this.form.startSoftwareFormData))
      );
    },
    // 监听软件停止脚本录入方式修改
    stopWayChange(val) {
      if (val === "上传") {
        // this.form.stopSoftwareFormData = {}
        if (!this.validatenull(this.stopScriptFileList)) {
          this.$nextTick(() => {
            this.$refs.stopScriptUpload.fileList = JSON.parse(
              JSON.stringify(this.stopScriptFileList)
            );
          });
        } else {
          this.$nextTick(() => {
            this.$refs.stopScriptUpload.fileList = [];
          });
        }
      } else if (val === "手动填写") {
        if (this.validatenull(this.form.stopSoftwareFormData)) {
          const data = {
            isDepPath: "绝对路径",
            stopPath: "",
            exeName: "",
          };
          this.form.stopSoftwareFormData = data;
        }
      }
    },
    // 保存软件停止表单数据
    saveStopSoftwareForm(data) {
      this.form.stopSoftwareFormData = data;
    },
    // 打开停止脚本表单
    openStopSoftwareForm() {
      this.$refs.stopSoftwareRef.openDialog(
        JSON.parse(JSON.stringify(this.form.stopSoftwareFormData))
      );
    },
    // 增加资源检查规则
    addDomain() {
      if (this.form.rules.length >= 2) return;
      this.form.rules.push({
        key: Date.now(),
        item: "",
        minvalue: "",
        unit: "",
      });
    },
    // 删除资源检查规则
    removeDomain(item) {
      if (this.form.rules.length > 1) {
        var index = this.form.rules.indexOf(item);
        if (index !== -1) {
          this.form.rules.splice(index, 1);
        }
      }
    },
    // 校验资源检查规则
    validFormRules() {
      let res = true;
      let itemArr = [];
      let errorMsg = ["资源检查规则填写有误："];
      this.form.rules.forEach((it, index) => {
        if (this.validatenull(it.item)) {
          errorMsg.push("第" + (index + 1) + "行类型不能为空");
          res = false;
        }
        if (this.validatenull(it.minvalue)) {
          errorMsg.push("第" + (index + 1) + "行数值不能为空");
          res = false;
        }
        if (this.validatenull(it.unit)) {
          errorMsg.push("第" + (index + 1) + "行单位不能为空");
          res = false;
        }
        if (itemArr.includes(it.item)) {
          errorMsg.push("第" + (index + 1) + "行类型不能重复");
          res = false;
        } else {
          itemArr.push(it.item);
        }
      });
      if (!res) {
        this.$message({
          showClose: false,
          dangerouslyUseHTMLString: true,
          message: errorMsg.join("<br>"),
          type: "error",
        });
      }
      return res;
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-scrollbar__wrap {
  overflow-x: hidden;
}
.el-alert--warning.is-light {
  background-color: white;
  color: rgb(0, 0, 0);
}
::v-deep .el-alert__icon {
  color: #e6a23c;
  font-size: 18px;
}
::v-deep .el-alert__title {
  font-size: 15px;
}
.pathDivider {
  margin: 5px 0;
}
::v-deep .domain-input-wrapper {
  width: 80%;
  .el-input-group__prepend {
    background-color: #fff;
  }
  .el-input-group__append {
    background-color: #fff;
  }
}
::v-deep .install-upload {
  .upload-file-uploader {
    .el-upload--text {
      display: none;
    }
  }
}
</style>
